<template>
	<view class="containerzi">
		<view @click="openPopup()">
			<view style="margin-bottom: 8rpx;">
				<text class="required-star">*</text>
				日期
			</view>
			<up-input placeholder="选择日期" v-model="value" :customStyle="{ width: '90vw', pointerEvents: 'none' }"
				readonly></up-input>
		</view>
		<!--  日期选择器  -->
		<up-datetime-picker title="选择日期" :show="show" v-model="dateValue" mode="date" @confirm="confirm"
			:closeOnClickOverlay="true" @close="closePopup" @cancel="show = false"></up-datetime-picker>

		<!--  订单客户信息  -->
		<view>
			<view style="margin-bottom: 8rpx;margin-top: 30rpx;">
				<text class="required-star">*</text>
				订单客户信息
			</view>
			<view>
				<scroll-view scroll-x="true" class="scroll-view">
					<view class="table-container">
						<table class="mobile-table order-table">
							<thead>
								<tr>
									<!-- <th class="sticky-header">序号</th> -->
									<th v-for="(item, index) in orderList" :key="index" class="nowrap">
										<view style="display:flex;">
											<text v-if="item.required" class="required-star">*</text>
											<view>{{ item.title }}</view>
										</view>
									</th>
								</tr>
							</thead>
							<tbody>
								<tr v-for="(row, rowIndex) in tableData" :key="rowIndex"
									@click="clickorder(row, rowIndex)">
									<!-- <td class="sticky-col">{{ rowIndex + 1 }}</td> -->
									<td v-for="(header, colIndex) in orderList" :key="colIndex" class="nowrap"
										:class="{ highlight: header.field === 'orderNum' }">
										{{ row[header.field] }}
									</td>
								</tr>
							</tbody>
						</table>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 要更正的客户信息  -->
		<view>
			<view style="margin-bottom: 8rpx;margin-top: 30rpx;">
				<text class="required-star">*</text>
				要更正的客户信息
			</view>
			<view>
				<scroll-view scroll-x="true" class="scroll-view">
					<view class="table-container">
						<table class="mobile-table">
							<thead>
								<tr>
									<!-- <th class="sticky-header">序号</th> -->
									<th v-for="(item, index) in productList" :key="index" class="nowrap">
										<view style="display:flex;">
											<text v-if="item.required" class="required-star">*</text>
											<view>{{ item.title }}</view>
										</view>
									</th>
								</tr>
							</thead>
							<tbody>
								<tr v-for="(row, rowIndex) in tableData" :key="rowIndex"
									@click="clickproduct(row, rowIndex)">
									<!-- <td class="sticky-col">{{ rowIndex + 1 }}</td> -->
									<td v-for="(header, colIndex) in productList.filter(h => h)" :key="colIndex"
										class="nowrap">
										{{ row[header.field] }}
									</td>
								</tr>
							</tbody>
						</table>
					</view>
				</scroll-view>

			</view>
		</view>

		<!-- 订单列表弹窗 -->
		<up-popup :z-index="99999" :show="showOrderListPopup" mode="right" @close="showOrderListPopup = false"
			:customStyle="{ height: '100vh', width: '100vw', borderRadius: '16rpx 0 0 16rpx' }">
			<up-navbar title="选择订单" @leftClick="showOrderListPopup = false" placeholder
				:customStyle="{ backgroundColor: '#fff', borderBottom: '1px solid #f5f5f5' }"></up-navbar>
			<view class="search-box">
				<u-input v-model="searchKeyword" placeholder="输入订单号或客户名称搜索" clearable
					@change="handleSearchInput"></u-input>
			</view>
			<view class="popup-containerd">

				<!-- #ifdef H5 -->
				<view style="height: 20rpx"></view>
				<!-- #endif -->

				<!-- #ifdef APP-PLUS -->
				<view style="height: 20rpx"></view>
				<!-- #endif -->

				<scroll-view scroll-y class="popup-scroll" @scrolltolower="loadMoreOrders">
					<view v-for="(order, index) in filteredOrders" :key="order.id" class="order-item"
						@click="selectOrderItem(order)">
						<view class="order-info">
							<text class="order-label">订单编号：</text>
							<text class="order-value">{{ order.order_sum }}</text>
						</view>
						<view class="order-arrow">
							<u-icon name="arrow-right" color="#999" size="16"></u-icon>
						</view>
					</view>
				</scroll-view>
			</view>
		</up-popup>
		<!-- 选择订单客户信息弹窗 -->
		<up-popup :show="showOrderPopup" mode="right" @close="showOrderPopup = false">
			<view class="popup-container">
				<up-navbar :placeholder="false" :title="'订单客户信息'" @leftClick="showOrderPopup = false"
					placeholder></up-navbar>
				<!-- #ifdef H5 -->
				<view style="height: 60rpx"></view>
				<!-- #endif -->

				<!-- #ifdef APP-PLUS -->
				<view style="height: 9vh"></view>
				<!-- #endif -->
				<scroll-view scroll-y class="popup-scroll">
          <!-- #ifdef H5 -->
          <view style="height: 60rpx"></view>
          <!-- #endif -->

          <!-- #ifdef APP-PLUS -->
          <view style="margin-top: 120rpx"></view>
          <!-- #endif -->
					<view class="popup-content">
						<up-form :model="currentOrder" :rules="orderRules" ref="orderForm" label-position="top">
							<up-form-item v-for="item in orderList" :key="item.field" :label="item.title"
								:required="item.required" :prop="item.field">
								<up-input @click="item.field === 'orderNum' ? openOrderListPopup() : null"
									v-model="currentOrder[item.field]" :placeholder="`请输入${item.title}`"
									:disabled="item.field !== 'orderNum'"></up-input>
							</up-form-item>
						</up-form>
						<up-button type="primary" @click="validateOrderForm" style="margin-bottom: 20rpx">保存</up-button>
					</view>
				</scroll-view>
			</view>
		</up-popup>


		<!-- 要更正的客户信息弹窗 -->
		<up-popup :show="showProductEditPopup" mode="right" @close="showProductEditPopup = false">
			<view class="popup-container">
				<up-navbar :placeholder="false" :title="'要更正的客户信息'" @leftClick="showProductEditPopup = false"
					placeholder></up-navbar>


				<scroll-view scroll-y class="popup-scroll">
          <!-- #ifdef H5 -->
          <view style="height: 60rpx"></view>
          <!-- #endif -->

          <!-- #ifdef APP-PLUS -->
          <view style="margin-top: 120rpx"></view>
          <!-- #endif -->
					<view class="popup-content">
						<up-form :model="currentProduct" :rules="productRules" ref="productForm" label-position="top">
							<up-form-item v-for="item in productList" :key="item.field" :label="item.title"
								:required="item.required" :prop="item.field">
								<!-- 其他输入项 -->
								<up-input v-model="currentProduct[item.field]"
									@click="item.field === 'customerName' ? showCustomerDialog() : null"
									:placeholder="`请输入${item.title}`"
									:disabled="item.field !== 'customerName'"></up-input>
							</up-form-item>
						</up-form>
						<up-button type="primary" @click="validateProductForm"
							style="margin-bottom: 20rpx">保存</up-button>
					</view>
				</scroll-view>
			</view>
		</up-popup>

		<up-popup :show="customerDialogVisible" mode="right" @close="customerDialogVisible = false">
			<view class="popup-container">
				<up-navbar :placeholder="false" :title="'选择客户'" @leftClick="customerDialogVisible = false"
					placeholder></up-navbar>

				<view class="popup-header-fixed">选择客户</view>

				<scroll-view scroll-y class="popup-scroll">
          <!-- #ifdef H5 -->
          <view style="height: 0rpx"></view>
          <!-- #endif -->

          <!-- #ifdef APP-PLUS -->
          <view style="height: 60rpx"></view>
          <!-- #endif -->

					<view class="popup-content">
						<!-- 搜索框 -->
						<view class="search-box">
							<up-input v-model="customerSearchQuery" placeholder="输入客户名称/编号搜索" clearable
								@confirm="handleCustomerSearch">
								<template #suffix>
									<up-icon name="search" size="20" @click="handleCustomerSearch"></up-icon>
								</template>
							</up-input>
						</view>

						<!-- 客户列表表格 -->
						<view class="customer-table">
							<scroll-view scroll-x class="table-scroll" @scrolltolower="loadMoreOrders">
								<table class="native-table">
									<thead>
										<tr>
											<th style="width: 200rpx;">客户名称</th>
											<th style="width: 150rpx;">所属部门</th>
											<th style="width: 120rpx;">销售人员</th>
											<th style="width: 120rpx;">付款账期</th>
											<th style="width: 150rpx;">所在区域</th>
											<th style="width: 120rpx;">客户形式</th>
											<th style="width: 120rpx;">收货人</th>
											<th style="width: 150rpx;">联系电话</th>
											<th style="width: 120rpx;">付款方式</th>
											<th style="width: 100rpx;">是否开票</th>
											<th>详细地址</th>
										</tr>
									</thead>
									<tbody>
										<tr v-for="(item, index) in filteredCustomerList" :key="index"
											:class="{ 'selected-row': selectedCustomer && selectedCustomer.customerId === item.customerId }"
											@click="handleCustomerRowClick(item)">
											<td>{{ item.customerName }}</td>
											<td>{{ item.departmentName }}</td>
											<td>{{ item.salePerson }}</td>
											<td>{{ item.accountPeriod }}</td>
											<td>{{ item.department }}</td>
											<td>{{ item.customerForm }}</td>
											<td>{{ item.customerTake }}</td>
											<td>{{ item.customerPhone }}</td>
											<td>{{ item.customerPay }}</td>
											<td>{{ item.isInvoicing }}</td>
											<td>{{ item.address }}</td>
										</tr>
									</tbody>
								</table>
							</scroll-view>
						</view>

						<!-- 操作按钮 -->
						<view class="action-buttons">
							<up-button type="default" @click="customerDialogVisible = false">取消</up-button>
							<up-button type="primary" @click="confirmCustomerSelection"
								style="margin-left: 20rpx">确定</up-button>
						</view>
					</view>
				</scroll-view>
			</view>
		</up-popup>

		<!-- 客户调整原因说明 -->
		<up-form :model="{ adjustReason }" :rules="adjustReasonRules" ref="adjustReasonForm">
			<up-form-item prop="adjustReason" label-position="top">
				<template #label>
					<view>
						<text class="required-star">*</text>
						客户调整原因说明
					</view>
				</template>
				<up-textarea placeholder="请输入调整原因（不少于10个字符）" v-model="adjustReason" :customStyle="textareaStyle"
					autoHeight @blur="handleReasonBlur"></up-textarea>
			</up-form-item>
		</up-form>
		<up-toast ref="uToastRef"></up-toast>
	</view>
</template>

<script>
import { GetgylList } from '@/apis/SupplyChain/orderAfterSales';
import { useUserStore } from "@/pinia-store/user.js";
import { mapStores } from 'pinia';
export default {
	name: "orderCustomerRename",
  props:{
    ApplyDetailList: {
      type: Array,
      default: () => {
        return []
      }
    },
    config: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
	data() {
		return {
			adjustReason: '', // 存储文本内容
			modalShow: false,
			show: false,
			dateValue: Number(new Date()),
			dateMode: '',
			value: '',
			textareaStyle: {
				minHeight: '200rpx',
				backgroundColor: '#fff',
				border: '1px solid #eaeaea',
				borderRadius: '8rpx',
			},
			orderList: [
				{ title: '订单编号', field: 'orderNum', required: true },
				{ title: '客户名称', field: 'customerName', required: true, disabled: true },
				{ title: '所属部门', field: 'department', required: true, disabled: true },
				{ title: '销售人员', field: 'salesPerson', required: true, disabled: true },
				{ title: '付款账期', field: 'accountPeriod', required: true, disabled: true },
				{ title: '所在区域', field: 'area', required: true, disabled: true },
				{ title: '客户形式', field: 'customerForm', required: true, disabled: true },
				{ title: '收货人', field: 'customerTake', required: true, disabled: true },
				{ title: '联系电话', field: 'customerPhone', required: true, disabled: true },
				{ title: '付款方式', field: 'customerPay', required: true, disabled: true },
				{ title: '是否开票', field: 'isInvoicing', required: true, disabled: true },
				{ title: '详细地址', field: 'address', required: true, disabled: true },
			], // 订单客户信息
			tableData: [{}], // 订单-客户信息
			productList: [
				{ title: '客户名称', field: 'customerName', required: true },
				{ title: '所属部门', field: 'department', required: true },
				{ title: '销售人员', field: 'salesPerson', required: true },
				{ title: '付款账期', field: 'accountPeriod', required: true },
				{ title: '所在区域', field: 'area', required: true },
				{ title: '客户形式', field: 'customerForm', required: true },
				{ title: '收货人', field: 'customerTake', required: true },
				{ title: '联系电话', field: 'customerPhone', required: true },
				{ title: '付款方式', field: 'customerPay', required: true },
				{ title: '是否开票', field: 'isInvoicing', required: true },
				{ title: '详细地址', field: 'address', required: true },
			], // 要更正的客户信息
			productData: [{}],
			// 订单选择列表

			// 弹出层控制
			showOrderPopup: false,
			showOrderEditPopup: false,
			showProductEditPopup: false,
			customerDialogVisible: false,
			showOrderListPopup: false,

			// 当前操作的数据
			currentRowIndex: null,
			// 初始化当前订单数据
			currentOrder: {
				orderNum: '', // 订单编号
				department: '', // 所属部门
				salesPerson: '', // 销售人员
				customerName: '', // 客户名称
				accountPeriod: '', // 付款账期
				area: '', // 所在区域
				customerForm: '', // 客户形式
				customerTake: '', // 收货人
				customerPhone: '', // 联系电话
				customerPay: '', // 付款方式
				isInvoicing: '', // 是否开票
				customerAddress: '', // 详细地址
				textProvince: '', // 省份
				textCity: '', // 城市
				textArea: '', // 区县
				address: '', // 拼接地址
			},
			// 初始化当前产品数据
			currentProduct: {
				customerName: '', // 客户名称
				department: '', // 所属部门
				salesPerson: '', // 销售人员
				accountPeriod: '', // 付款账期
				area: '', // 所在区域
				customerForm: '', // 客户形式
				customerTake: '', // 收货人
				customerPhone: '', // 联系电话
				customerPay: '', // 付款方式
				isInvoicing: '', // 是否开票
				customerAddress: '', // 详细地址
				textProvince: '', // 省份
				textCity: '', // 城市
				textArea: '', // 区县
				address: '', // 拼接地址
			},

			selectedCustomer: null,
			customerSearchQuery: '',
			searchKeyword: '',

			pageNum: 1,
			pageSize: 15,
			total: 0,
			allGylorderNO: [],
			customerList: [], // 所有客户列表
			isLoadingOrders: false,
			noMoreOrders: false,
			tempOrderData: null,
			tempProductData: null,
			// 订单校验规则
			orderRules: {
				orderNum: [{ required: true, message: '请输入订单编号', trigger: 'change' }],
			},
			// 客户信息校验规则
			productRules: {
				customerName: [{ required: true, message: '请输入客户名称', trigger: 'change' }],
			},
			adjustReasonRules: {
				adjustReason: [{ required: true, message: '请输入调整原因', trigger: 'change' }],
			},
		}
	},
	created() {
    uni.setStorageSync('orderAfterSalesData', null);
    uni.setStorageSync('orderCustomerRenameData', null);
    uni.$on('orderCustomerRename',(order)=>{
      this.selectOrderItem(order)
    })
		// this.gGetgylList()
    this.handleDataEcho()
	},
	computed: {
		...mapStores(useUserStore),
		filteredOrders() {
			if (!this.searchKeyword) {
				return this.allGylorderNO; // 没有搜索关键词时返回全部数据
			}
			const keyword = this.searchKeyword.toLowerCase();
			return this.allGylorderNO.filter(order => {
				return (
					(order.order_sum && order.order_sum.toLowerCase().includes(keyword)) ||
					(order.customer_name && order.customer_name.toLowerCase().includes(keyword))
				);
			});
		},
		//客户列表过滤
		filteredCustomerList() {
			if (!this.customerSearchQuery) {
				return this.customerList;
			}
			const query = this.customerSearchQuery.toLowerCase();
			return this.customerList.filter(item =>
				(item.customerName && item.customerName.toLowerCase().includes(query)) ||
				(item.customerCode && item.customerCode.toLowerCase().includes(query))
			);
		}
	},
	methods: {
    handleDataEcho() {
   if (!this.ApplyDetailList.formData) return;

    const fieldValue = this.ApplyDetailList.formData[this.config.id];
    if (!fieldValue) return;

    try {
      const data = typeof fieldValue === "string" ? JSON.parse(fieldValue) : fieldValue;

      this.value = data.date || "";
      this.adjustReason = data.reason || "";

      this.tableData = Array.isArray(data.orderCustomer) && data.orderCustomer.length > 0 ? data.orderCustomer : [{}];

      this.productData = Array.isArray(data.customerList) && data.customerList.length > 0 ? data.customerList : [{}];

      this.currentOrder = {
        ...this.currentOrder,
        ...(this.tableData[0] || {})
      };
      this.currentProduct = {
        ...this.currentProduct,
        ...(this.productData[0] || {})
      };

      // 更新本地存储
      this.updateLocalStorage();
    } catch (e) {
      console.error("客户订单更名流程单回显失败:", e, fieldValue);
    }
    },
		handleSearchInput() {
			// 重置分页参数
			this.pageNum = 1;
			this.noMoreOrders = false;

			// 如果有搜索关键词，使用本地过滤
			if (this.searchKeyword) {
				return;
			}

			// 没有搜索关键词时重新加载数据
			this.allGylorderNO = [];
			this.loadMoreOrders();
		},
		// 显示客户选择对话框
		showCustomerDialog() {
			this.customerDialogVisible = true;
			this.selectedCustomer = null;
			this.customerSearchQuery = '';
			this.loadMoreOrders()
		},

		// 客户行点击
		handleCustomerRowClick(row) {
			this.selectedCustomer = row;
		},

		// 客户搜索
		handleCustomerSearch() {
			// 重置分页参数
			this.pageNum = 1;
			this.noMoreOrders = false;

			// 如果有搜索关键词，使用本地过滤
			if (this.searchKeyword) {
				return;
			}

			// 没有搜索关键词时重新加载数据
			this.allGylorderNO = [];
			this.loadMoreOrders();
		},

		// 确认客户选择
		confirmCustomerSelection() {
			if (!this.selectedCustomer) {
				uni.showToast({
					title: '请先选择一个客户',
					icon: 'none'
				});
				return;
			}

			// 更新表单中的客户信息
			const customer = this.selectedCustomer;
			this.formData.customerList[0].customerId = customer.customerId || '';
			this.formData.customerList[0].customerName = customer.customerName || '';
			// ...其他字段赋值...

			this.customerDialogVisible = false;
		},

		// 打开弹窗时重置分页
		openOrderListPopup() {
      uni.navigateTo({
        url: `/pages/apply/form/components/showOrderListPopup?SupplyChain=orderCustomerRename`
      });
			// this.pageNum = 1
			// this.allGylorderNO = []
			// this.noMoreOrders = false
			// this.showOrderListPopup = true
			// this.loadMoreOrders()
		},

		async loadMoreOrders() {
			// 如果有搜索关键词，不执行上拉加载
			if (this.searchKeyword) return;
			// 防止重复加载或已加载全部
			if (this.isLoadingOrders || this.noMoreOrders) return;

			this.isLoadingOrders = true;
			try {
				const res = await GetgylList({
					token: this.userStore.user.token,
					type: 1,
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					orderNumber: ''
				});

				if (res.status == 1) {
					// 确保数据格式正确
					const records = res.data?.records || [];
					this.total = res.data?.total || 0;

					// 处理第一页加载的情况
					if (this.pageNum === 1) {
						this.allGylorderNO = records;
					} else {
						this.allGylorderNO.push(...records);
					}

					// 判断是否还有更多数据
					if (records.length < this.pageSize || this.allGylorderNO.length >= this.total) {
						this.noMoreOrders = true;
					} else {
						this.pageNum += 1;
					}
				} else {
					uni.showToast({
						title: res.message || '加载失败',
						icon: 'none'
					});
				}
				this.modalShow = false
			} catch (err) {
				this.modalShow = false
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'none'
				});
			} finally {
				this.modalShow = false
				this.isLoadingOrders = false;
			}
		},
		// 选中订单
		selectOrderItem(order) {
			this.searchKeyword = ''
			// 将选中的订单数据填充到当前编辑的订单表单中
			this.currentOrder = {
				...this.currentOrder,
				orderNum: order.order_sum || '', // 订单编号
			};
			this.GetgylList(order.order_sum)
			// 关闭订单选择弹窗
			this.showOrderListPopup = false;
		},
		async GetgylList(value) {
			try {
				this.modalShow = true;
				const res = await GetgylList({
					token: this.userStore.user.token,
					type: 4,
					orderNum: value,
				});

				if (res.status === 1 && res.data) {
					const orderData = res.data;
					const address = [
						orderData.textProvince,
						orderData.textCity,
						orderData.textArea,
						orderData.customerAddress
					].map(item => item ? item.trim() : '')
						.filter(item => item)
						.join(' ');
					// 暂存订单数据到临时变量
					this.tempOrderData = {
						orderNum: orderData.orderSum || '',
						department: orderData.department || '',
						salesPerson: orderData.salesPerson || '',
						customerName: orderData.customerName || '',
						accountPeriod: orderData.accountPeriod || '',
						area: orderData.area || '',
						customerForm: orderData.customerForm || '',
						customerTake: orderData.customerTake || '',
						customerPhone: orderData.customerPhone || '',
						customerPay: orderData.customerPay || '',
						isInvoicing: orderData.isInvoicing == 1 ? '是' : '否' || '',
						customerAddress: orderData.customerAddress || '',
						textProvince: orderData.textProvince || '',
						textCity: orderData.textCity || '',
						textArea: orderData.textArea || '',
						address: address || '',
					};

					// 暂存产品数据到临时变量
					this.tempProductData = {
						department: orderData.department || '',
						salesPerson: orderData.salesPerson || '',
						customerName: orderData.customerName || '',
						accountPeriod: orderData.accountPeriod || '',
						area: orderData.area || '',
						customerForm: orderData.customerForm || '',
						customerTake: orderData.customerTake || '',
						customerPhone: orderData.customerPhone || '',
						customerPay: orderData.customerPay || '',
						isInvoicing: orderData.isInvoicing == 1 ? '是' : '否' || '',
						customerAddress: orderData.customerAddress || '',
						textProvince: orderData.textProvince || '',
						textCity: orderData.textCity || '',
						textArea: orderData.textArea || '',
						address: address || '',
					}

					// 更新当前订单表单数据（仅用于显示）
					this.currentOrder = { ...this.tempOrderData };
					this.currentProduct = { ...this.tempProductData };
				}
			} catch (error) {
				console.error('获取订单详情出错:', error);
			} finally {
				this.modalShow = false;
			}
		},

		// 处理单选框变化
		radiochange(e) {
			this.currentProduct.saleType = e;

			// 设置显示状态
			const shouldShow = e === '折价';
			this.currentProduct.show = shouldShow;

			// 如果是折价，初始化字段
			if (e === '折价') {
				this.currentProduct.compensationQuantity = this.currentProduct.compensationQuantity || '';
				this.currentProduct.discountPrice = this.currentProduct.discountPrice || '';
				this.calculateActualPayable(this.currentProduct);
			} else {
				// 如果是退货，清空相关字段
				this.currentProduct.compensationQuantity = '';
				this.currentProduct.discountPrice = '';
				this.currentProduct.actualPayableAmount = '';
			}
		},
		openPopup() {
			this.show = true;
		},
		closePopup() {
			this.show = false;
		},
		// 选中时间
		confirm(event) {
			var date = this.formatTimestampToYYMMDD(event.value);
			this.value = date;
			this.show = false;

			// 更新本地缓存并通知父组件
			this.updateLocalStorage();
		},
		// 失去焦点时触发
		handleReasonBlur() {
			this.updateLocalStorage(); // 更新本地缓存
		},
		// 更新本地缓存并通知父组件
		updateLocalStorage() {
			const cachedData = {
				orderCustomer: this.tableData,
				customerList: this.productData,
				date: this.value,
				reason: this.adjustReason
			};

			uni.setStorageSync('orderAfterSalesData', cachedData);

			// 触发事件通知父组件数据已更新
			this.$emit('data-updated', cachedData);
		},
		// 打开选择订单弹窗
		openOrderSelect() {
			this.showOrderPopup = true
		},

		// 选择订单
		selectOrder(order) {
			this.tableData = [order]
			this.showOrderPopup = false
		},

		// 点击订单行
		clickorder(row, rowIndex) {
			this.currentOrder = {
				...this.currentOrder, // 保留初始化结构
				...row // 覆盖实际数据
			}
			this.currentRowIndex = rowIndex
			this.showOrderPopup = true
		},

		// 点击产品行
		clickproduct(row, rowIndex) {
			this.currentRowIndex = rowIndex;
			// 深拷贝当前行数据
			this.currentProduct = JSON.parse(JSON.stringify(row));

			// 初始化显示状态
			this.currentProduct.show = this.currentProduct.saleType === '折价';

			// 如果是折价且数据完整，则计算金额
			if (this.currentProduct.saleType === '折价' &&
				this.currentProduct.compensationQuantity &&
				this.currentProduct.discountPrice) {
				this.calculateActualPayable(this.currentProduct);
			}

			this.showProductEditPopup = true;
		},

		// 校验订单表单
		validateOrderForm() {
			// this.$refs.orderForm.validate().then((res) => {
			// 	if (res) {
			// 		// 校验通过后，将临时数据更新到表格中
			// 		if (this.tempOrderData && this.tempProductData) {
			// 			this.tableData = [this.tempOrderData];
			// 			this.productData = [this.tempOrderData];

			// 			// 清空临时数据
			// 			this.tempOrderData = null;
			// 			this.tempProductData = null;

			// 			this.updateLocalStorage();

			// 			// 关闭弹窗
			// 			this.showOrderPopup = false;
			// 		}
			// 	}
			// }).catch((errors) => {
			// 	uni.showToast({
			// 		title: '请填写完整订单信息',
			// 		icon: 'none',
			// 	});
			// });

      this.$refs.orderForm.validate().then((res) => {
        if (res) {
          // 订单
          if (this.tempOrderData) {
            this.tableData = [this.tempOrderData];
            this.tempOrderData = null;
          }

          // 产品
          if (this.tempProductData) {
            this.productData = [this.tempProductData];
            this.tempProductData = null;
          }

          // 同步本地存储
          this.updateLocalStorage();

          // 关闭弹窗
          this.showOrderPopup = false;
        }
      })
      .catch(() => {
        uni.showToast({
          title: '请填写完整订单信息',
          icon: 'none',
        });
      });
		},

		// 校验产品表单
		validateProductForm() {
			this.$refs.productForm.validate().then(res => {
				if (res) {
					this.saveProductEdit()
					this.updateLocalStorage();
				}
			}).catch(errors => {
				uni.showToast({
					title: '请填写完整订单信息',
					icon: 'none'
				})
			})
		},

		saveProductEdit() {
			// 保存前重新计算确保数据准确
			if (this.currentProduct.saleType === '折价') {
				this.calculateActualPayable(this.currentProduct);
			}

			// 更新到产品数据
			this.$set(this.productData, this.currentRowIndex, {
				...this.currentProduct,
				show: this.currentProduct.saleType === '折价'
			});
			this.showProductEditPopup = false;
		},
		// 时间戳转换
		formatTimestampToYYMMDD(timestamp) {
			const date = new Date(timestamp);
			const year = date.getFullYear().toString();
			const month = ('0' + (date.getMonth() + 1)).slice(-2);
			const day = ('0' + date.getDate()).slice(-2);
			const hour = ('0' + date.getHours()).slice(-2);
			const minute = ('0' + date.getMinutes()).slice(-2);
			if (this.dateMode === 'date') {
				return `${year}-${month}-${day}`;
			} else if (this.dateMode === 'datetime') {
				return `${year}-${month}-${day} ${hour}:${minute}`;
			} else if (this.dateMode === 'year-month') {
				return `${year}-${month}`;
			}
			return `${year}-${month}-${day}`; // 返回 YYMMDD 格式的字符串
		}
	}
}
</script>

<style scoped lang="scss">
.containerzi{
  background-color: #ffffff
}

.order-item {
	padding: 20rpx;
	border-bottom: 1px solid #eee;
}

.loading-text,
.no-more-text {
	text-align: center;
	color: #888;
	padding: 20rpx 0;
}

/* 隐藏字段样式 */
.hidden-field {
	display: none;
}

::v-deep uni-button {
	margin-left: 0 !important;
	margin-right: 10rpx !important;
	border: none !important;
}

.table-container {
	width: 100%;
}

/* 订单表格专属优化 */
.order-table {

	th,
	td {
		width: auto;

		&:first-child {
			width: auto;
		}
	}

	/* 交替行背景色 */
	tr:nth-child(even) td {
		background-color: #fafafa;
	}

	/* 重要数据突出显示 */
	.highlight {
		color: #e74c3c;
		font-weight: 500;
	}
}

.scroll-view {
	width: 95vw;
	white-space: nowrap;
	padding: 10rpx 0;
}

.mobile-table {
	width: auto;
	min-width: 100%;
	border-collapse: separate;
	border-spacing: 0;

	th,
	td {
		padding: 16rpx 24rpx;
		border-bottom: 1px solid #eee;
		font-size: 26rpx;
		line-height: 1.4;
	}

	th {
		background: #f1f2f4;
		color: #333;
		font-weight: 500;
		position: relative;

		&:not(:first-child)::after {
			content: "";
			position: absolute;
			right: 0;
			top: 10%;
			height: 80%;
			width: 1px;
			background: #ddd;
		}
	}

	td {
		color: #666;
		background: #fff;
	}

	.sticky-header {
		position: sticky;
		left: 0;
		z-index: 2;
		width: auto;
	}

	.sticky-col {
		position: sticky;
		left: 0;
		background: #f9f9f9;
		z-index: 1;
	}
}

.nowrap {
	white-space: nowrap;
}

.required-star {
	color: #e74c3c;
	margin-right: 4rpx;
	font-size: 28rpx;
	vertical-align: middle;
}

:required {
	border-left: 4rpx solid #e74c3c;
}


.popup-content {
	padding: 30rpx;
	background: #fff;
	border-radius: 20rpx 20rpx 0 0;

	.popup-header {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
		text-align: center;
	}

	.order-item {
		padding: 20rpx;
		border-bottom: 1px solid #eee;
		display: flex;
		justify-content: space-between;

		&:active {
			background-color: #f5f5f5;
		}
	}
}

.popup-container {
	width: 100vw;
	height: 100%;
	background-color: #f3f3f3;
	display: flex;
	flex-direction: column;
}

.popup-containerd {
	background-color: #f5f5f5;
	padding: 0 20rpx;
	height: calc(100vh - 100rpx);
}

.popup-scroll {
	height: 100% !important;
}

.search-box {
	//margin-bottom: 20rpx;
	background: #fff;
	border-radius: 12rpx;
	padding: 10rpx 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}



.order-item {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	position: relative;
	display: flex;
	flex-direction: column;
	transition: all 0.2s;

	&:active {
		background-color: #f8f8f8;
		transform: scale(0.99);
	}
}

.order-info {
	display: flex;
	margin-bottom: 12rpx;
	font-size: 28rpx;

	&:last-child {
		margin-bottom: 0;
	}
}

.order-label {
	color: #666;
	width: 140rpx;
}

.order-value {
	color: #333;
	flex: 1;
	font-weight: 500;
}

.order-arrow {
	position: absolute;
	right: 24rpx;
	top: 50%;
	transform: translateY(-50%);
}

.loading-text,
.no-more-text {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 30rpx 0;
	color: #999;
	font-size: 26rpx;

	text {
		margin-top: 16rpx;
	}
}

.u-page {
	padding: 0;
}

.u-cell-icon {
	width: 36rpx;
	height: 36rpx;
	margin-right: 8rpx;
}

.u-cell-group__title__text {
	font-weight: bold;
}

:deep(.u-form-item__body__right__message) {
	margin-left: 0 !important;
}

.popup-container {
	width: 100vw;
	height: 100vh;
	background-color: #fff;
}

.popup-header-fixed {
	padding: 20rpx 30rpx;
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	background-color: #f8f8f8;
}

.popup-scroll {
	height: calc(100vh - 180rpx);
	flex: 1;
	padding-bottom: 120rpx;
	/* 给底部按钮留出空间 */
}

.popup-content {
	padding: 30rpx;
}



.customer-table {
	margin-bottom: 30rpx;
	overflow-x: auto;
}

.selected-row {
	background-color: #f0f7ff;
}

.pagination-container {
	margin: 30rpx 0;
}

.action-buttons {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx 30rpx;
	background-color: #fff;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	display: flex;
	justify-content: flex-end;
	z-index: 10;
}

.table-container {
	width: 100%;
	margin-bottom: 30rpx;
}

.table-scroll {
	width: 100%;
	overflow-x: auto;
}

.native-table {
	width: 100%;
	border-collapse: collapse;
	font-size: 28rpx;
}

.native-table th,
.native-table td {
	padding: 16rpx 20rpx;
	border: 1px solid #ebeef5;
	text-align: left;
	white-space: nowrap;
}

.native-table th {
	background-color: #f5f7fa;
	color: #909399;
	font-weight: bold;
}

.native-table tr:hover {
	background-color: #f5f7fa;
}

.selected-row {
	background-color: #f0f7ff !important;
}
</style>
